package yunquan.wang.modules.base.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import yunquan.wang.base.dao.springdata.BaseRepository;
import yunquan.wang.base.dao.springdata.RepositoryUtils;
import yunquan.wang.base.service.impl.BaseServiceImpl;
import yunquan.wang.base.web.TreePojo;
import yunquan.wang.modules.base.dao.AuthorityTypeDao;
import yunquan.wang.modules.base.entity.AuthorityType;
import yunquan.wang.modules.base.service.AuthorityTypeService;
/**
 *  AuthorityType Service层 实现
 *  @author 王云权  wangyunquan@gmail.com
 *  用生成器 生成于 2011-09-30 22:37
 *
 */
@Service("authorityTypeService")
@Transactional(value = "jpaTransaction")
public class AuthorityTypeServiceImpl extends BaseServiceImpl<AuthorityType>
		implements AuthorityTypeService {
	@Resource 
	private AuthorityTypeDao authorityTypeDao;


 
	public BaseRepository<AuthorityType, String> getDao() {
		return authorityTypeDao;
	}
	public List<TreePojo> getAuthorityTree()
	{
		List<TreePojo> list = new ArrayList<TreePojo>();
		AuthorityType top=	authorityTypeDao.findOne(RepositoryUtils.eq("name", "AUTH_"));
		if(top==null)
		{
			top=initAuthType();
		}
		list.addAll(getSubAuthorityType(top,"0"));
		return list;
	}

	public AuthorityType save(AuthorityType entity)
	{
		if(StringUtils.isBlank(entity.getId())){
	String parentId=entity.getParent().getId();
    String parentName=authorityTypeDao.findOne(parentId).getName();
    entity.setName(parentName+"_"+entity.getName());
		}
		authorityTypeDao.save(entity);
		return entity;
	}
	
	/**
	 * 初始化权限类型
	 * 
	 * @return
	 */
	public AuthorityType initAuthType() {
		AuthorityType authType = new AuthorityType();
		authType.setId("1");
		authType.setCnname("权限类型");
		authType.setName("AUTH_");
		return authorityTypeDao.save(authType);
	}
	
	private List<TreePojo> getSubAuthorityType(AuthorityType authType,
			String parentId) {
		List<TreePojo> list = new ArrayList<TreePojo>();
		TreePojo topNode = new TreePojo(authType.getId(), parentId,
				authType.getCnname());
		list.add(topNode);
		for (AuthorityType child : authType.getChilds()) {
			list.addAll(getSubAuthorityType(child, authType.getId()));
		}
		return list;
	}

}
